<template>
  <div id="userLayout" :class="['user-layout-wrapper', isMobile && 'mobile']">
    <div class="container">
      <div class="top">
        <div class="header">
          <a href="/">
            <img alt="logo" class="logo" src="~@/assets/logo.svg">
            <span class="title">{{ systemName }}</span>
          </a>
        </div>
      </div>
      <div :class="[ isMobile && 'mobile']" :style="backgroundImage" class="main">
        <div class="content">
          <a-form-model id="formLogin" ref="formLogin" :model="form" :rules="rules" @submit="handleSubmit">
            <a-tabs
                :activeKey="customActiveKey"
                :tabBarStyle="{ textAlign: 'left'}"
                style=" margin-top: -20px;"
                @change="handleTabClick"
            >
              <a-tab-pane key="tab1" tab="账号密码登录">
                <a-row :gutter="16">
                  <a-col :span="24">
                    <a-form-model-item prop="userName">
                      <a-input
                          v-model="form.userName"
                          placeholder="账户"
                          size="large"
                          type="text"
                      >
                        <a-icon slot="prefix" type="user"/>
                      </a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row :gutter="16">
                  <a-col :span="24">
                    <a-form-model-item prop="userPassword">
                      <a-input
                          v-model="form.userPassword"
                          autocomplete="false"
                          placeholder="密码"
                          size="large"
                          type="password"
                      >
                        <a-icon slot="prefix" type="lock"/>
                      </a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row :gutter="16">
                  <a-col :span="15">
                    <a-form-model-item prop="imgCode1">
                      <a-input v-model="form.imgCode1" placeholder="图片验证码" size="large" type="text"
                               @change="imgCodeChange">
                        <a-icon slot="prefix" type="picture"/>
                      </a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="9">
                    <img :src="imgSrc" class="getCaptcha" mode="" @click="initCode"/>
                  </a-col>
                </a-row>
                <a-row :gutter="16">
                  <a-col :span="24">
                    <a-form-model-item prop="currentDataScope">
                      <a-select v-model="form.currentDataScope" placeholder="请选择">
                        <a-select-option v-for="item in dataScope" :key="item.dictKey" :value="item.dictKey">
                          {{ item.dictValue }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-tab-pane>
              <a-tab-pane key="tab2" tab="手机号登录">
                <a-row :gutter="16">
                  <a-col :span="24">
                    <a-form-model-item prop="cellphone">
                      <a-input
                          v-model="form.cellphone"
                          placeholder="手机号"
                          size="large"
                          type="text"
                      >
                        <a-icon slot="prefix" :style="{ color: 'rgba(0,0,0,.25)' }" type="mobile"/>
                      </a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row :gutter="16">
                  <a-col :span="15">
                    <a-form-model-item prop="imgCode">
                      <a-input v-model="form.imgCode" placeholder="图片验证码" size="large" type="text"
                               @change="imgCodeChange">
                        <a-icon slot="prefix" :style="{ color: 'rgba(0,0,0,.25)' }" type="picture"/>
                      </a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="9">
                    <img :src="imgSrc" class="getCaptcha" mode="" @click="initCode"/>
                  </a-col>
                </a-row>
                <a-row :gutter="16">
                  <a-col :span="15">
                    <a-form-model-item prop="shortMsgCode">
                      <a-input v-model="form.shortMsgCode" placeholder="验证码" size="large" type="text">
                        <a-icon slot="prefix" :style="{ color: 'rgba(0,0,0,.25)' }" type="mail"/>
                      </a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="9">
                    <a-button
                        :disabled="disableCodeBtn"
                        class="getCaptcha"
                        tabindex="-1"
                        @click="sentMessage"
                        v-text="!state.smsSendBtn && state.smsText || (state.time+' s')"
                    ></a-button>
                  </a-col>
                </a-row>
              </a-tab-pane>
            </a-tabs>
            <a-row :gutter="16">
              <a-col :span="24">
                <div class="register-forge">
                  <router-link
                      :to="{ name: 'register',query:{userType:userType} }"
                      class="forge-password"
                  >注册用户
                  </router-link>
                  <router-link
                      :to="{ name: 'forgePassword',query:{userType:userType} }"
                      class="forge-password"
                  >忘记密码
                  </router-link>
                </div>
              </a-col>
              <a-col :span="24">
                <div style="padding-top:5px">
                  <a-button
                      :disabled="state.loginBtn"
                      :loading="state.loginBtn"
                      class="login-button"
                      htmlType="submit"
                      size="large"
                      type="primary"
                  >登<span style="width:20px"></span>录
                  </a-button>
                </div>
              </a-col>

            </a-row>


          </a-form-model>
        </div>
      </div>
      <div class="footer">
        <div class="copyright">
          {{ copyright }}
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import md5 from 'md5'
import store from '@/store'
import {mapActions, mapState} from 'vuex'
import {getBrowerInfo, uuid} from '@/utils/util'
// import validate from '@/utils/validate'
import {getImgCode, loginSendMessage} from "@/services/system/api"

const dataScope = [
  {dictKey: 'busiSuperAdmin', dictValue: '超级管理员平台'},
  {dictKey: '330300000000', dictValue: '温州市数据区平台'},
  {dictKey: '330302', dictValue: '鹿城区数据区平台'},
  {dictKey: '330303', dictValue: '龙湾区数据区平台'},
  {dictKey: '330304', dictValue: '瓯海区数据区平台'},
  {dictKey: '330305', dictValue: '洞头区数据区平台'},
  {dictKey: '330382', dictValue: '乐清市数据区平台'},
  {dictKey: '330381', dictValue: '瑞安市数据区平台'},
  {dictKey: '330383', dictValue: '龙港市数据区平台'},
  {dictKey: '330329', dictValue: '泰顺县数据区平台'},
  {dictKey: '330324', dictValue: '永嘉县数据区平台'},
  {dictKey: '330326', dictValue: '平阳县数据区平台'},
  {dictKey: '330327', dictValue: '苍南县数据区平台'},
  {dictKey: '330328', dictValue: '文成县数据区平台'},
]

export default {
  data() {
    return {
      dataScope,
      windowHeight: document.documentElement.clientHeight, //实时屏幕高度
      windowWidth: document.documentElement.clientWidth,  //实时屏幕宽度
      loginKey: uuid(),
      form: {
        userName: null,
        userPassword: null,
        imgCode: null,
        imgCode1: null,
        shortMsgCode: null,
        cellphone: null,
        currentDataScope: null
      },
      imgSrc: null,
      state: {
        time: 60,
        loginBtn: false,
        // login type: 6 email, 1 username, 2 telephone
        loginType: 6,
        smsSendBtn: false,
        smsText: '获取验证码'
      },
      userType: '10',
      customActiveKey: 'tab1',
      loginType: 'username',
      isLoginError: false,
      disableCodeBtn: true,
      showImgCode: false,
      browser: getBrowerInfo(),
      rules: {
        userName: [
          {required: true, message: '请输入用户名'},
        ],
        userPassword: [
          {required: true, message: '请输入密码'},
        ],
        imgCode: [
          {required: true, message: '请输入图片验证码'},
        ],
        imgCode1: [
          {required: true, message: '请输入图片验证码'},
        ],
        shortMsgCode: [
          {required: true, message: '请输入短信验证码'},
        ],
        cellphone: [
          {required: true, pattern: /^1[345789]\d{9}$/, message: '请输入正确的手机号'}
        ],
        currentDataScope: [
          {required: true, message: "请选择平台"}
        ],
      }
    }
  },
  created() {
    this.initCode()
  },
  watch: {
    windowHeight(val) {
      let that = this;
      console.log("实时屏幕高度：", val, that.windowHeight);
    },
    windowWidth(val) {
      let that = this;
      console.log("实时屏幕宽度：", val, that.windowHeight);
    }
  },
  computed: {
    ...mapState('setting', ['isMobile', 'loginBgImg', 'copyright', 'systemName']),
    backgroundImage() {
      // 根据背景图数组的长度随机选择索引
      // const randIndex = Math.floor(Math.random() * this.loginBgImg.length)
      let height = this.windowHeight - 221
      // if (this.loginBgImg.length === 0 || this.isMobile) {
      //   return null
      // }
      // let str = this.loginBgImg[randIndex]
      // let img = null
      // if (validate.isUrl(str)) {
      //   img = str
      // } else {
      //   img = require(`@/assets/bg/${str}`);
      // }
      let img = '';
      return `min-height:400px;background-size: 100% 100%;background-repeat: no-repeat;background-image:url(${img}); height: ${height}px;`
    }
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    initCode() {
      this.imgSrc = getImgCode + '?loginKey=' + this.loginKey + '&time=' + new Date().getTime()
    },
    imgCodeChange(e) {
      const imgCode = e.target.value || ''
      if (this.state.smsSendBtn) {
        this.disableCodeBtn = true
        return
      }
      if (imgCode.length < 4) {
        this.disableCodeBtn = true
      } else {
        this.disableCodeBtn = false
      }
    },
    handleTabClick(key) {
      this.customActiveKey = key
      const form = Object.assign({}, this.form)
      form.imgCode = ''
      form.imgCode1 = ''
      this.form = form
      this.initCode()
      if (key === 'tab2') {
        this.loginType = 'cellphone'
      } else if (key === 'tab1') {
        this.loginType = 'username'
      }
    },
    sentMessage(e) {
      e.preventDefault()
      console.log("发送短信");
      const state = this.state
      if (state.smsSendBtn) {
        return
      }
      let flag = this.checkForm(['cellphone', 'imgCode'])
      if (flag) {
        state.smsSendBtn = true
        const interval = window.setInterval(() => {
          if (state.time-- <= 0) {
            state.time = 60
            state.smsSendBtn = false
            state.smsText = '重新发送'
            window.clearInterval(interval)
          }
        }, 1000)
        const hide = this.$message.loading('验证码发送中..', 0)
        const data = {}
        // data.cellphone = values.cellphone
        // data.imgCode = values.imgCode
        data.loginKey = this.loginKey
        data.userType = this.userType
        this.$http.post(loginSendMessage, data).then(() => {
          setTimeout(hide, 100)
          this.$notification['success']({
            message: '提示',
            description: '发送短信验证码成功',
            duration: 4
          })
        }).catch(err => {
          setTimeout(hide, 1)
          clearInterval(interval)
          state.time = 60
          state.smsSendBtn = false
          state.smsText = '获取验证码'
          this.requestFailed(err)
        })
      }
    },
    checkForm(props) {
      let flag = true
      if (props && props.length > 0) {
        this.$refs.formLogin.validateField(props, errorMessage => {
          if (errorMessage) {
            flag = false
          }
        });
      } else {
        this.$refs.formLogin.validate(valid => {
          if (valid) {
            flag = true
          } else {
            flag = false
          }
        });
      }
      return flag
    },
    handleSubmit(e) {
      e.preventDefault()
      const {
        form,
        state,
        customActiveKey,
        Login,
        loginType,
        loginKey,
        userType,
        browser
      } = this
      state.loginBtn = true
      const validateFieldsKey = customActiveKey === 'tab1' ? ['userName', 'userPassword', 'imgCode1'] : ['cellphone', 'shortMsgCode', 'imgCode']
      let flag = this.checkForm(validateFieldsKey)
      if (flag) {
        const loginParams = {}
        loginParams.loginType = loginType
        loginParams.userType = userType
        loginParams.equipmentType = 'pc'
        loginParams.browser = browser.browserType
        loginParams.loginKey = loginKey
        loginParams.version = store.state.version
        loginParams.systemCode = store.state.systemCode
        loginParams.systemName = store.state.systemName
        if (loginType === 'username') {
          loginParams.userPassword = md5(form.userPassword)
          loginParams.userName = form.userName
          loginParams.imgCode = form.imgCode1
          loginParams.currentDataScope = form.currentDataScope
        } else if (loginType === 'cellphone') {
          loginParams.cellphone = form.cellphone
          loginParams.shortMsgCode = form.shortMsgCode
          loginParams.imgCode = form.imgCode
        }
        Login(loginParams)
            .then((res) => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
            })
      } else {
        setTimeout(() => {
          state.loginBtn = false
        }, 600)
      }
    },
    loginSuccess(res) {
      console.log(res)
      // check res.homePage define, set $router.push name res.homePage
      // Why not enter onComplete
      /*
      this.$router.push({ name: 'analysis' }, () => {
          console.log('onComplete')
          this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
          })
      })
      */
      this.$router.push({name: this.$store.state.user.homeName})
      // 延迟 1 秒显示欢迎信息
      /**
       setTimeout(() => {
                    this.$notification.success({
                    message: '欢迎',
                    description: `${timeFix()}，欢迎回来`
                    })
                }, 1000)
       */
      this.isLoginError = false
    },
    requestFailed(error) {
      this.isLoginError = true
      if (error.code === 40101) {
        this.showImgCode = true
        this.initCode()
      }
    }
  },
}
</script>

<style lang="less" scoped>
#userLayout.user-layout-wrapper {
  height: 100%;


  &.mobile {
    .container {
      .top {
        text-align: center;

        .header {
          padding-left: 0;
        }
      }
    }
  }

  .container {
    width: 100%;
    height: 100%;
    background: #f5f6f7;
    background-size: 100%;
    padding: 64px 0 54px 0;
    position: relative;
    background: url("~@/assets/img/login-bg.png") no-repeat center / 100%;

    a {
      text-decoration: none;
    }

    .top {
      text-align: left;
      padding-bottom: 15px;

      .header {
        height: 33px;
        line-height: 33px;
        padding-left: 50px;

        .badge {
          position: absolute;
          display: inline-block;
          line-height: 1;
          vertical-align: middle;
          margin-left: -12px;
          margin-top: -10px;
          opacity: 0.8;
        }

        .logo {
          height: 33px;
          vertical-align: top;
          margin-right: 16px;
          border-style: none;
        }

        .title {
          font-size: 26px;
          color: #ffffff;
          font-family: Avenir, 'Helvetica Neue', Arial, Helvetica, sans-serif;
          font-weight: 600;
          position: relative;
          top: 2px;
        }
      }

      .desc {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.45);
        margin-top: 12px;
        margin-bottom: 40px;
      }
    }


    .footer {
      width: 100%;
      bottom: 0;
      padding: 0 16px;
      margin: 10px 0 24px;
      text-align: center;

      .links {
        margin-bottom: 8px;
        font-size: 14px;

        a {
          color: rgba(0, 0, 0, 0.45);
          transition: all 0.3s;

          &:not(:last-child) {
            margin-right: 40px;
          }
        }
      }

      .copyright {
        color: rgba(0, 0, 0, 0.45);
        font-size: 14px;
      }
    }
  }
}

&.mobile {
  .main {
    padding-right: 0;
    justify-content: center;
  }
}

.main {
  width: 100%;
  height: calc(~"100% - 80px");

  display: flex;
  align-items: center;
  justify-content: flex-end;
  vertical-align: center;
  padding-right: 150px;

  .content {
    width: 360px;
    height: 420px;
    background: rgba(0, 0, 0, 0.8);
    border: 1px solid #8AD8FF;
    --ShadowSize: 0px 20px 50px 0px;
    border-radius: 8px;
    padding: 35px
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
    background-image: linear-gradient(45deg, #2756B0, #2F84F0)
  }

  .register-forge {
    display: flex;
    align-items: center;
    justify-content: space-between;
    vertical-align: center;
  }

  .forge-password {
    font-size: 12px;
    color: #777777;
  }
}

</style>
